#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.minio.policy;

import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 读写策略
 */
@Slf4j
public class BucketReadWriterPolicy implements BucketPolicy {

    /**
     * 桶占位符
     */
    private static final String BUCKET_PARAM = "${symbol_dollar}{bucket}";

    /**
     * bucket权限-读写
     */
    private static final String READ_WRITE = "{${symbol_escape}"Version${symbol_escape}":${symbol_escape}"2012-10-17${symbol_escape}",${symbol_escape}"Statement${symbol_escape}":[{${symbol_escape}"Effect${symbol_escape}":${symbol_escape}"Allow${symbol_escape}",${symbol_escape}"Principal${symbol_escape}":{${symbol_escape}"AWS${symbol_escape}":[${symbol_escape}"*${symbol_escape}"]},${symbol_escape}"Action${symbol_escape}":[${symbol_escape}"s3:GetBucketLocation${symbol_escape}",${symbol_escape}"s3:ListBucket${symbol_escape}",${symbol_escape}"s3:ListBucketMultipartUploads${symbol_escape}"],${symbol_escape}"Resource${symbol_escape}":[${symbol_escape}"arn:aws:s3:::" + BUCKET_PARAM + "${symbol_escape}"]},{${symbol_escape}"Effect${symbol_escape}":${symbol_escape}"Allow${symbol_escape}",${symbol_escape}"Principal${symbol_escape}":{${symbol_escape}"AWS${symbol_escape}":[${symbol_escape}"*${symbol_escape}"]},${symbol_escape}"Action${symbol_escape}":[${symbol_escape}"s3:DeleteObject${symbol_escape}",${symbol_escape}"s3:GetObject${symbol_escape}",${symbol_escape}"s3:ListMultipartUploadParts${symbol_escape}",${symbol_escape}"s3:PutObject${symbol_escape}",${symbol_escape}"s3:AbortMultipartUpload${symbol_escape}"],${symbol_escape}"Resource${symbol_escape}":[${symbol_escape}"arn:aws:s3:::" + BUCKET_PARAM + "/*${symbol_escape}"]}]}";


    @Override
    public boolean createBucketPolicy(MinioClient client, String bucket) {
        try {
            client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucket).config(READ_WRITE.replace(BUCKET_PARAM, bucket)).build());
            return true;
        } catch (InvalidKeyException | ErrorResponseException | InsufficientDataException | InternalException
                | InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException
                | IllegalArgumentException | IOException e) {
            log.error("error: {}", e.getMessage(), e);
        }
        return false;
    }
}
